package com.leetcode.题库;

/**
 * @author 覃国强
 * @date 2022-02-26 11:13
 */
public class 题库_0008_字符串转换整数atoi {

  public static void main(String[] args) {
    String s = "21474836460";
    Solution solution = new Solution();
    int answer = solution.myAtoi(s);
    System.out.println(answer);
  }

  static
  class Solution {
    public int myAtoi(String s) {
      // 去除前导空格
      if (s != null) {
        s = s.trim();
      }
      if (s == null || s.length() == 0) {
        return 0;
      }

      char[] chars = s.toCharArray();
      // 判断符号
      int symbol = 1;
      int i = 0;
      if (chars[0] == '-' || chars[0] == '+') {
        symbol = chars[0] == '-' ? -1 : 1;
        i = 1;
      }

      // 去除前导 0
      while (i < chars.length && chars[i] == '0') {
        ++i;
      }
      if (i == chars.length) {
        return 0;
      }

      // 计算数字
      int answer = 0;
      for (; i < chars.length && answer < Integer.MAX_VALUE / 10; ++i) {
        if (Character.isDigit(chars[i])) {
          int curNum = Integer.parseInt(Character.toString(chars[i]));
          answer = answer * 10 + curNum;
        } else {
          break;
        }
      }

      // 处理边界
      if (i < chars.length - 1 && Character.isDigit(chars[i]) && Character.isDigit(chars[i + 1]) && answer >= Integer.MAX_VALUE / 10) {
        return symbol == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
      }
      if (i < chars.length && Character.isDigit(chars[i])) {
        if (answer == Integer.MAX_VALUE / 10) {
          int curNum = Integer.parseInt(Character.toString(chars[i]));
          // 正数
          if (symbol == 1 && curNum >= 7) {
            return Integer.MAX_VALUE;
          }
          // 负数
          if (symbol == -1 && curNum >= 8) {
            return Integer.MIN_VALUE;
          }
          answer = answer * 10 + curNum;
        } else if (answer > Integer.MAX_VALUE / 10) {
          return symbol == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
      }

      return symbol * answer;
    }
  }

}
